package com.xuecheng.content.service.iml;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.mapper.CourseMarketMapper;
import com.xuecheng.content.service.CourseBaseService;
import com.xuecheng.model.PageParams;
import com.xuecheng.model.PageResult;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.model.dto.AddCourseDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.EditCourseDto;
import com.xuecheng.content.model.enums.InseartCourseBaseError;
import com.xuecheng.base.execption.XueChengPlusException;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.po.CourseBase;
import com.xuecheng.content.model.po.CourseMarket;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 课程信息管理业务接口实现类
 */
@RequiredArgsConstructor
@Service
public class CourseBaseServiceIml extends ServiceImpl<CourseBaseMapper, CourseBase>implements CourseBaseService {

    private final CourseBaseMapper courseBaseMapper;

    private final CourseMarketMapper courseMarketMapper;

    private  final CourseCategoryMapper courseCategoryMapper;
    /**
     * 课程信息分页查询
     * @param pageParams
     * @param queryCourseParamsDto
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()),CourseBase::getName,queryCourseParamsDto.getCourseName());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,queryCourseParamsDto.getAuditStatus());
        //课程机构
        queryWrapper.eq(CourseBase::getCompanyId,companyId);
//构建查询条件，根据课程发布状态查询

        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;

    }

    /**
     * 新增课程信息
     * @param addCourseDto
     * @return
     */
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto) {
        //课程名称为空
        if(addCourseDto.getName().isEmpty()){
            throw new XueChengPlusException(InseartCourseBaseError.COURSR_NAME_EMPTY.getDescription());
        }
        //适用人群为空
        if(addCourseDto.getUsers().isEmpty()){
            throw new XueChengPlusException(InseartCourseBaseError.SUITABLE_PEOPER_EMPTY.getDescription());
        }
        //教育模式
        if(addCourseDto.getTeachmode().isEmpty()){
            throw new XueChengPlusException(InseartCourseBaseError.EDUCATIONAL_MODEL_EMPTY.getDescription());
        }
        //课程大分类为空
        if(addCourseDto.getMt().isEmpty()){
            throw new XueChengPlusException(InseartCourseBaseError.MAXCOURSE_CLASS_EMPTY.getDescription());
        }
        //课程小分类为空
        if(addCourseDto.getSt().isEmpty()){
            throw new XueChengPlusException(InseartCourseBaseError.MINCOURSE_CLASS_EMPTY.getDescription());
        }
        //课程等级为空
        if(addCourseDto.getGrade().isEmpty()){
            throw  new XueChengPlusException(InseartCourseBaseError.COURSR_GRADE_EMPTY.getDescription());
        }
        //设置添加参数
        CourseBase courseBase = BeanUtil.copyProperties(addCourseDto, CourseBase.class);
        courseBase.setCompanyId(companyId);
        courseBase.setAuditStatus("202002");
        courseBase.setCreateDate(LocalDateTime.now());
        courseBase.setStatus("203001");
        int insert = courseBaseMapper.insert(courseBase);
        if(insert<=0){
            throw new XueChengPlusException(InseartCourseBaseError.INSERT_COUESR_ERROR.getDescription());
        }
        //向课程营销表保存课程营销信息
        //设置添加营销表的参数
        CourseMarket courseMarket = BeanUtil.copyProperties(addCourseDto, CourseMarket.class);
        courseMarket.setId(courseBase.getId());
        int i = saveCourseMarket(courseMarket);
        if(i<=0){
            throw new XueChengPlusException("新增营销表失败");
        }
        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseBase.getId());

    }

    /**
     * 根据课程id查询基本信息
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseById(Long courseId) {
        return getCourseBaseInfo(courseId);
    }

    /**
     * 修改课程接口
     *
     * @param editCourseDto
     * @return
     */
    public CourseBaseInfoDto modifCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //更新基本信息
        //1.1查询课程是否存在
        CourseBase courseBaseOld = courseBaseMapper.selectById(editCourseDto.getId());
        if(courseBaseOld==null){
            throw new XueChengPlusException("课程不存在");
        }
        //1.2校验与数据库机构是否相同
        if(!courseBaseOld.getCompanyId().equals(companyId)){
            throw new XueChengPlusException("本机构只能修改本机构的课程");
        }
        CourseBase courseBase = BeanUtil.copyProperties(editCourseDto, CourseBase.class);
        courseBase.setChangeDate(LocalDateTime.now());
        int i = courseBaseMapper.updateById(courseBase);
        if(i<=0){
            throw new XueChengPlusException("更新基本信息失败");
        }
        //更新营销信息
        CourseMarket courseMarket = BeanUtil.copyProperties(editCourseDto, CourseMarket.class);
        int j = saveCourseMarket(courseMarket);
        if(j<=0){
            throw new XueChengPlusException("更新营销信息失败");
        }
        //查询课程基本信息及营销信息并返回
        return getCourseBaseInfo(courseBase.getId());
    }

    @Override
    public void deleteCourseBase(Long id) {
        courseBaseMapper.deleteById(id);
    }

    /**
     * 查询课程基本信息及营销信息并返回
     * @param id
     * @return
     */
    public CourseBaseInfoDto getCourseBaseInfo(Long id) {
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        //查询基本信息
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if(courseBase == null){
            return null;
        }
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        //查询营销表
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        }
        //查询分类名称
        CourseCategory courseCategory = courseCategoryMapper.selectById(courseBase.getSt());
        courseBaseInfoDto.setStName(courseCategory.getName());
        CourseCategory courseCategory1 = courseCategoryMapper.selectById(courseBase.getMt());
        courseBaseInfoDto.setMtName(courseCategory1.getName());
        return courseBaseInfoDto;
    }


    /**
     * 向课程营销表保存课程营销信息
     * @param courseMarket
     * @return
     */
    private int saveCourseMarket(CourseMarket courseMarket) {
        String charge = courseMarket.getCharge();
        //收费规则不能为空
        if(charge.isEmpty()){
            throw new XueChengPlusException("收费规则为空");
        }
        //收费时，收费不能为空,小于0
        if(charge.equals("201001")){
            if(courseMarket.getPrice()==null||courseMarket.getPrice()<=0){
                throw new XueChengPlusException("有收费时，收费不能为空或小于等于0");
            }
        }
        //判断营销表中是否已有数据
        CourseMarket courseMarket1 = courseMarketMapper.selectById(courseMarket.getId());
        if(courseMarket1==null){
            //未有数据，加入数据
            return  courseMarketMapper.insert(courseMarket);
        }else {
            //已有数据，更新数据
            return courseMarketMapper.updateById(courseMarket);
        }
    }


}
